package ca.ets.osgi.conferenceroomservice;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;


public class RoomReader {
	
	
	private ListRooms lr;
	/**
	 * Constructor
	 */
	public RoomReader(){}
	
	/**
	 * Make a list of Rooms
	 */
	public void openList(){
		lr = ListRooms.getInstance();
		System.out.println("------------Trying to load and fill the list of rooms------------");
		try {
			File fXmlFile = new File("C://temp/ca.ets.osgi.conferenceroomservice/src/ca/ets/osgi/conferenceroomservice/rooms2.xml");
			//File fXmlFile = new File("C://eclipse/Workspace/ca.ets.osgi.conferenceroomservice/src/ca/ets/osgi/conferenceroomservice/rooms2.xml");
			//File fXmlFile = new File("flights.xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);
			doc.getDocumentElement().normalize();
			NodeList roomList = doc.getElementsByTagName("Room");
			for (int temp = 0; temp < roomList.getLength(); temp++) {
				Node roomNode = roomList.item(temp);
				if (roomNode.getNodeType() == Node.ELEMENT_NODE) {
					Element elem = (Element) roomNode;
					Room room = new Room();
					room.setName(elem.getAttribute("rid").trim());
					String boo = getValue("projector",elem);
					boolean projector = false;
					if(boo.equalsIgnoreCase("true")){
						projector = true;
					}
					room.setProjectorAvailable(projector);
					room.setSurface(getValue("surface",elem));
					lr.addRoomToList(room.getName(), room);
				}
				
			}
			System.out.println("------------The list of rooms have been loaded------------");
			System.out.println("");
			
		}catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
	    }
		
	}
	private static String getValue(String tag, Element element) {
		NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
		Node node = (Node) nodes.item(0);
		return node.getNodeValue();
	}

}
